package com.yg.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yg.config.FilePathConfig;
import com.yg.config.result.R;
import com.yg.config.result.ResultCode;
import com.yg.entity.readAndWriteTemplates.TeacherAppointTemplate;
import com.yg.entity.singleEntity.TeacherAppoint;
import com.yg.listener.TeacherAppointReadListener;
import com.yg.mapper.TeacherAppointMapper;
import com.yg.service.TeacherAppointService;
import com.yg.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 对应sheet03，此表为教师挂职表
 * 注意！此表的id和教师表的id是一个id 服务实现类
 * </p>
 *
 * @author YingGu
 * @since 2020-11-04
 */
@Service
public class TeacherAppointServiceImpl extends ServiceImpl<TeacherAppointMapper, TeacherAppoint> implements TeacherAppointService {

    @Autowired
    private FilePathConfig config;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private TeacherAppointMapper teacherAppointMapper;

    /**
     * 读取表格数据插入到数据库中
     *
     * @param file 文件
     * @param r    返回的结果
     */
    @Transactional
    @Override
    public void readExcel(MultipartFile file, R r) {

        try {

            InputStream inputStream = file.getInputStream();

            EasyExcel.read(inputStream, TeacherAppointTemplate.class, new TeacherAppointReadListener(this, teacherService, r)).headRowNumber(3).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            r.code(ResultCode.IMPORT_TABLE_EXCEPTION);
        }
    }

    /**
     * 读取数据库中的数据写入到表格中
     *
     * @param appointTemplate
     * @param response
     */
    @Transactional
    @Override
    public void writeExcel(TeacherAppointTemplate appointTemplate, HttpServletResponse response) {

        //模板文件
        String fileTemplate = config.getWriteExcelFilePath() + "sheet03Template.xlsx";

        List<TeacherAppointTemplate> teacherAppointTemplateList = teacherAppointMapper.writeExcel(appointTemplate);

        int i = 1;
        for (TeacherAppointTemplate teacherAppointTemplate : teacherAppointTemplateList) {
            teacherAppointTemplate.setNums(String.valueOf(i++));
            countBirthday(teacherAppointTemplate);
        }

        //导出(匿名内部类SheetWriteHandler)

        response.setHeader("Content-disposition", "attachment;filename=" + "sheet03Write.xlsx");
        try {
            EasyExcel.write(response.getOutputStream()).withTemplate(fileTemplate).registerWriteHandler(new SheetWriteHandler() {

                @Override
                public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {

                }

                @Override
                public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
                    //日志
                }


            }).sheet().doFill(teacherAppointTemplateList);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 条件查询带分页
     *
     * @param current         当前页
     * @param limit           每页显示的条目
     * @param appointTemplate 查询条件
     * @param vip             权限
     * @param teacherId
     * @return
     */
    @Override
    public R getTeacherAppoint(long current, long limit, TeacherAppointTemplate appointTemplate, String vip, String teacherId) {
        try {
            long total;
            List<TeacherAppointTemplate> list = null;
            if (vip.equals("v1")) {
                list = teacherAppointMapper.getTeacherAppoint(current, limit, appointTemplate);
                total = teacherAppointMapper.getTeacherAppointPages(appointTemplate);
            } else {
                list = teacherAppointMapper.getTeacherAppointById(current, limit, appointTemplate, teacherId);
                total = teacherAppointMapper.getTeacherAppointByIdPages(appointTemplate, teacherId);
            }
            Long pages = (total / limit) + 1;

            list.forEach(e -> {
                countBirthday(e);
            });


            return R.OK().data("teacherAppointList", list).data("total", total).data("pages", pages);
        } catch (Exception e) {
            e.printStackTrace();
            return R.ERROR();
        }
    }

    /**
     * 计算生日
     *
     * @param teacherAppointTemplate
     */
    private void countBirthday(TeacherAppointTemplate teacherAppointTemplate) {
        if (teacherAppointTemplate != null && !StringUtils.isEmpty(teacherAppointTemplate.getBirthday())) {
            Integer birthday = Integer.valueOf(teacherAppointTemplate.getBirthday().substring(0, 4));
            int now = LocalDateTime.now().getYear();
            teacherAppointTemplate.setAge(now - birthday);
        }
    }
}
